#include <app\states\textureTileState.h>
#include <app\states\statesFactory.h>
#ifdef CLIENT
#include <network\streamingClient.h>
#endif
#include <cache\textureCacheKey.h>

int textureTileState::class_type_id = TEXTURE_TILE_STATE_TYPE_ID;

REGISTER_STATE(TEXTURE_TILE_STATE_TYPE_ID, textureTileState);

sessionState *
textureTileState::create() {
  return new textureTileState();
} 

bool 
textureTileState::isReady() {
  return texture_tile_desc.status == nTextureTile::READY;
}

void
textureTileState::setState(nTextureTile::eTextureTile s) {
  
  #ifdef CLIENT
  if (s == nTextureTile::TRANSFERRED) {
    // notify source of this request that data was downloaded
    caller->get()->terrainDownloaded();
    delete caller;
  }
  #endif

  texture_tile_desc.status = s;
}

#ifdef SERVER
void 
textureTileState::requestTextureTile(int x, int y, int level) {

  if (isReady()) {
    setState(nTextureTile::TRANSFERRING);
    
    texture_tile_desc.x = x;
    texture_tile_desc.y = y;
    texture_tile_desc.level = level;
  }
}
#endif

#ifdef CLIENT
void 
textureTileState::requestTextureTile(int x, int y, int level, tile * caller_) {

  if (isReady()) {
    setState(nTextureTile::TRANSFERRING);
    
    texture_tile_desc.x = x;
    texture_tile_desc.y = y;
    texture_tile_desc.level = level;
  }
}

void 
textureTileState::receivedTextureTile(int x, int y, int level, unsigned char *data, int size) {
  texture_tile_desc.x = x;
  texture_tile_desc.y = y;
  texture_tile_desc.level = level;

  textureCacheKey *terr_cache = static_cast<textureCacheKey *>(cacheKeysFactory::instance().createCacheKey(CACHE_KEY_TEXTURE, parent));
  terr_cache->init(x, y, level);
  terr_cache->setData(data, size, false);
  terr_cache->save();
  delete terr_cache;

  setState(nTextureTile::TRANSFERRED);
}
#endif
int 
textureTileState::getClassTypeId() {
  return textureTileState::class_type_id;
}

int 
textureTileState::getTypeId() {
  return type_id;
}

textureTileState::textureTileState() : type_id(TEXTURE_TILE_STATE_TYPE_ID) {

}

textureTileState::~textureTileState() {

}
